#include "localMovieListMessageHandler.h"
#include "localMovieListMessage.h"
#include "localMovieListInfoMessage.h"
#include "movieService.h"

void LocalMovieListMessageHandler::handle(Message<String>* message, const IPaddress& attachment)
{
    LocalMovieListMessage* msg = (LocalMovieListMessage*)message;
    int page = msg->getPage();
    if (page < 1) page = 1;
    int limit = msg->getLimit();
    if (limit < 1) {
        limit = 1;
    }
    if (limit > 50) {
        limit = 50;
    }
    const std::list<Movie*>& list = MovieService::inst().getMovies();
    std::list<Movie*> dataList;
    bool nameFilter = !msg->getName().empty();
    for (std::list<Movie*>::const_iterator it = list.begin(); it != list.end(); ++it) {
        if (nameFilter) {
            String::size_type pos = (*it)->getName().find(msg->getName());
            if (pos != String::npos) {
                dataList.push_back(*it);
            }
        }
        else {
            dataList.push_back(*it);
        }
    }
    int pages = (dataList.size() / limit) + (dataList.size() % limit == 0 ? 0 : 1);
    if (page > pages)
    {
        page = pages;
    }
    int offset = (page - 1) * limit;
    int count = dataList.size() - offset;
    count = count > limit?limit:count;
    int idx = 0; 
    std::list<Movie*>::const_iterator it = dataList.begin();
    while (idx < offset)
    {
        ++it;
        ++idx;
    }
    std::list<Movie*> records;
    while (it != dataList.end() && idx < offset + count)
    {
        records.push_back(*it);
        ++it;
        ++idx;
    }
    LocalMovieListInfoMessage local(dataList.size(), limit, page, pages, records,msg);
    local.send(attachment);
}

Message<String>* LocalMovieListMessageHandler::decode(Protocol<String>* packet, const IPaddress& attachment)
{
    return new LocalMovieListMessage((MtpProtocol*)packet);
}
